package org.finesys.common.redisson.service.impl;

import lombok.RequiredArgsConstructor;
import org.finesys.common.redisson.constants.RedissonLockType;
import org.finesys.common.redisson.entity.LockEntity;
import org.finesys.common.redisson.service.RedissonService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

/**
 * 可重入锁
 */
@RequiredArgsConstructor
public class RedissonReentrantLockServiceImpl implements RedissonService {

    private final RedissonClient redissonClient;

    @Override
    public boolean lock(LockEntity lockEntity) {
        //获取锁
        RLock rLock = redissonClient.getLock(lockEntity.getLockName());
        try {
            //加锁
            return rLock.tryLock(lockEntity.getWaitTime(), lockEntity.getLeaseTime(), lockEntity.getTimeUnit());
        } catch (InterruptedException e) {
            return false;
        }
    }

    @Override
    public void unlock(LockEntity lockEntity) {
        //获取锁
        RLock rLock = redissonClient.getLock(lockEntity.getLockName()); //释放锁
        if (rLock.isHeldByCurrentThread()) {
            rLock.unlockAsync();
        }
    }

    @Override
    public RedissonLockType lockType() {
        return RedissonLockType.REENTRANT;
    }
}
